import axios from 'axios'
const baseUrl = 'http://localhost:8080/server/'

axios.defaults.withCredentials = true;
const apiAxios = async (method, url, params) => {
    //项目既定fapp
    let headers = { 'Content-Type': 'application/x-www-form-urlencoded' }
    //读取存储在sessionStorage中的token
    var token = sessionStorage.getItem("token");
    if (token != null) {
        // console.log(data);
        headers.token = token;
        // console.log("token: "+headers.token);
    }
    return await new Promise((resolve => {
        axios({
            //如果缓存里有token则所有请求都包含其
            headers: headers,
            method: method,
            url: baseUrl + url,
            //数据内容
            data:
                method === 'POST' ? params : null,
            params:
                method === 'GET' ? params : null
        }).then((res) => {
            console.log(res.data)
            resolve(res.data)
        }).catch(e => {
            console.log(e)
        })
    }))
}
//get请求
const api = {
    //get请求
    async get(url, params,) {
        // console.log(baseUrl + url)
        return await apiAxios('GET', url, params)
    },
    //post请求
    async post(url, params) {
        // console.log(baseUrl + url)
        return await apiAxios('POST', url, params)
    }
}
export default api
